import { s_getcommontableinfo, s_getQuotePrice, s_operate2data, state2text, status2text } from "@/services/basis";
import { CheckOutlined } from "@ant-design/icons";
import { ActionType, EditableFormInstance, EditableProTable, ProCard, ProColumns, ProForm, ProFormCheckbox, ProFormInstance, ProTable } from "@ant-design/pro-components";
import { Button, Col, Divider, message, Row, Space } from "antd";
import moment from "moment";
import { useRef, useState } from "react";

const App:React.FC=()=>{
    const [dataSourceByDetail,setDataSourceByDetail]=useState([]);
    const [detailType,setDetailType]=useState(1);
    const [minTotal,setMinTotal]=useState([]);
    const [selectType,setSelectType]=useState<any[]>([0]);
    const [selectedRecord,setSelectedRecord]=useState<DataType[]>([]);

    const table_ref=useRef<ActionType>();
    const editor_ref=useRef<EditableFormInstance>();

   interface DataType{
    id:number,code:string,order_code:string,status:number,state:number,querytype:number,
    valid_begindate:string,valid_enddate:string,pricetype:string,
   }
   const columns:ProColumns<DataType>[]=[
    {dataIndex:'id',title:'ID'},{dataIndex:'code',title:'询价单号'},{dataIndex:'order_code',title:'订单号'},
    {dataIndex:'state',title:'定价状态',
      render:(text:any)=>text==11?<>已定价</>:<>未定价/{state2text(1,text)}</>,
    },
    {dataIndex:'status',title:'报价状态',
      render:(text:any)=>status2text(text),
    }
   ];
   
   //明细报价组件
   function TableByDetail(props:any){
      const setData=props.setData;
      const data=props.data;

      const formRef=useRef<ProFormInstance>();

      interface DataType{
        rid:number,id:number,material_id:number,material_code:string,material_name:string,
        userdefine_name:string,vendor_name:string,memo:string,state:number,invstd:string,invstd2:string,
        price:number,taxrate:number,total:number,minquantity:number,munit_name:string,
        ischoose:number,userdefine_id:string,
      };
      const columns:ProColumns<DataType>[]=[
        {dataIndex:'rid',title:'rid',valueType:'digit',editable:false,},{dataIndex:'id',title:'ID',editable:false,},
        {dataIndex:'material_id',title:'物料ID',editable:false,},{dataIndex:'material_name',title:'物料名称',editable:false,},
        {dataIndex:'invstd',title:'规格',editable:false,},{dataIndex:'invstd2',title:'型号',editable:false,},
        {dataIndex:'userdefine_name',title:'属性',editable:false,},{dataIndex:'munit_name',title:'主单位',editable:false,},
        {dataIndex:'vendor_name',title:'供应商',editable:false,},{dataIndex:'memo',title:'说明',editable:false,},
        {dataIndex:'price',title:'含税价',editable:false,},{dataIndex:'taxrate',title:'税率%',editable:false,},
        {dataIndex:'total',title:'含侻金额',editable:false,},{dataIndex:'minquantity',title:'起订量',editable:false,},
        {dataIndex:'userdefine_id',hidden:true},
        {dataIndex:'ischoose',title:'选择',
          fixed:'right',width:80,
          valueType:'select',
          valueEnum:{1:{text:<CheckOutlined/>}},
          // valueEnum:{true:{text:'选'}}
        },
        {
          valueType:'option',
          title:'操作',
          fixed:'right',
          width:80,
          render:(text,record,_,action)=>[
            <a onClick={()=>{
              action?.startEditable?.(record.rid);
            }}>
              编辑
            </a>
          ]
        },
      ]; 
       
      return <>
            <ProForm submitter={false} formRef={formRef}>
            <EditableProTable<DataType>
              rowKey='rid'
              editableFormRef={props.editor_ref}
              columns={columns}
              search={false}
              name='editotable'
              recordCreatorProps={false}
              value={data}
              request={async ()=>{
                  return {
                     data,
                      success:true,
                  }}}
              editable = {{                       // defaultDom = {save,cancel,delete} 可以酌情添加和使用
                   actionRender: (row, config, defaultDom) => [
                          defaultDom.save,
                        //   defaultDom.cancel,
                        ],
                        type:'multiple',
                      }}
              />
            </ProForm>
         </>

   }

   //整单报价组件
   function TableByVouch(props:any){
    const [vouchDetail,setVouchDetail]=useState([]);

    const setData=props.setData;
    const data=props.data;
    
    
    const formRef=useRef<ProFormInstance>();

    //明细表
    interface DataType{
      id:number,material_id:number,material_code:string,material_name:string,
      userdefine_name:string,vendor_name:string,memo:string,state:number,invstd:string,invstd2:string,
      price:number,taxrate:number,total:number,minquantity:number,munit_name:string,
      ischoose:number, 
    };
    const columns:ProColumns<DataType>[]=[
      {dataIndex:'id',title:'ID',},{dataIndex:'material_id',title:'物料ID',},
      {dataIndex:'material_name',title:'物料名称',},{dataIndex:'invstd',title:'规格',},{dataIndex:'invstd2',title:'型号',},
      {dataIndex:'userdefine_name',title:'属性'},{dataIndex:'munit_name',title:'主单位',},{dataIndex:'memo',title:'说明',},
      {dataIndex:'price',title:'含税价',},{dataIndex:'taxrate',title:'税率%',},{dataIndex:'total',title:'含侻金额',},
      {dataIndex:'minquantity',title:'起订量'},{dataIndex:'ischoose',title:'选择',},
    ]; 

    //主表
    interface DataType2{
      rid:number,id:number,vendor_id:number,vendor_name:string,x_id:number,
      quantity:number,
      // taxrate:number,
      total:number,nettotal:number,ischoose:number,
    }

    const columns2:ProColumns<DataType2>[]=[
      {dataIndex:'rid',title:'rid',valueType:'digit',editable:false,},
      {dataIndex:'id',title:'ID',editable:false,},{dataIndex:'vendor_id',title:'供应商ID',editable:false,},
      {dataIndex:'vendor_name',title:'供应商名',editable:false,},{dataIndex:'quantity',title:'总数量',editable:false,},
      // {dataIndex:'taxrate',title:'税率%'},
      {dataIndex:'total',title:'总含税金额',editable:false,},
      {dataIndex:'nettotal',title:'总不含税金额',editable:false,},
      {dataIndex:'ischoose',title:'选择',fixed:'right',width:80,
        valueType:'select',
        valueEnum:{1:{text:<CheckOutlined/>}},
      },
      {
        valueType:'option',
        title:'操作',
        width:80,
        fixed:'right',
        render:(text,record,_,action)=>[
          <a onClick={()=>{
            action?.startEditable?.(record.rid);
          }}>
            编辑
          </a>
        ]
      },
    ];
     
    return <>
          <ProForm submitter={false} formRef={formRef} >
          <ProCard style={{height:600,overflow:'auto'}}>
              <EditableProTable<DataType2>
                editableFormRef={props.editor_ref}
                rowKey='rid'
                columns={columns2}
                search={false}
                name='editortable'
                recordCreatorProps={false}
                dataSource={data}
                rowSelection={{
                  type:'radio',
                  async  onChange(selectedRowKeys, selectedRows, info) {
                      // alert(JSON.stringify(selectedRows[0]));
                    // if(selectedRows.length>1){
                       const x=await s_getcommontableinfo({x_id:1,source:'v_quoteprice_detail',id:0,
                            fdata:{mid:selectedRows[0].id,vendor_id:selectedRows[0].vendor_id}});
                        // alert(JSON.stringify(x.data[0]));
                       setVouchDetail(x.data[0]);
                    // }
                  },
                }}
                request={async ()=>{
                  return {
                    data,
                    success:true,
                  }
                }}
                editable = {{                       // defaultDom = {save,cancel,delete} 可以酌情添加和使用
                  actionRender: (row, config, defaultDom) => [
                         defaultDom.save,
                       //   defaultDom.cancel,
                       ],
                       type:'multiple',
                     }}
                />
            <Divider>物料明细价格</Divider>
            {JSON.stringify(vouchDetail)}
            <ProTable<DataType>
                  rowKey='id'
                  columns={columns}
                  search={false}
                  name='detailtable'
                  toolBarRender={false}
                  dataSource={vouchDetail}
            />
            </ProCard>
          </ProForm>
       </>

 }
 
 //批量选择最低价
 function chooseMinTotal(){
    // alert(JSON.stringify(editor_ref.current?.getRowsData?.()));
    //  alert(JSON.stringify(minTotal));
    const x=editor_ref.current?.getRowsData?.();
    x?.map((item:any)=>{
       const y1=item.rid;
       minTotal.map((item2:any)=>{
          const z1=item2.rid;
          if(y1==z1){
            // alert(y1);
            // alert(z1);  
             editor_ref?.current?.setRowData?.(item.rid.toString().toString(),{ischoose:1});
          }
       });
    });
 }

 //核准价格1,核准并生成采购单2
 async function verifyPrice(etype:number){
  const x0=editor_ref.current?.getRowsData?.();
  const x1=x0?.filter((item:any)=>item.ischoose==1);
  const x=x1?.map((item:any)=>( 
                   {...item,
                      deliverdate:moment(moment(item.deliverdate).toDate()).format('YYYY-MM-DD'),
                      valid_begindate:moment(moment(selectedRecord[0].valid_begindate).toDate()).format('YYYY-MM-DD'),
                      valid_enddate:moment(moment(selectedRecord[0].valid_enddate).toDate()).format('YYYY-MM-DD'),
                      querytype:selectedRecord[0].querytype,
                    }));
   
  alert(JSON.stringify(x));
  // source,x_id,operater_id,etype,otype,id,tdata
  //注意：etype:1核准价格--生成价格表，2核准并生成采购订单
  if(x?.length==0)
    message.warning('请先选择价格供应商');
  else{
  const y=await s_operate2data({source:'verifyprice_do',x_id:1,operater_id:1,
                                  etype,otype:0,id:0,tdata:{head:selectedRecord[0],detail:x}});
  if(y.success){
       message.success('定价成功');
    }else{
       message.error('定价失败，请联系管理员');
    };
  };
 }

//  主页面输出=======================================================================================================
    return <>
          <Row gutter={8}>
            <Col span={8}>
              <ProCard title='询价清单' style={{height:700}}
                extra={<Space>
                    <ProFormCheckbox.Group name='shows'  
                    fieldProps={{
                        defaultValue:selectType,
                        onChange(checkedValue) {
                          // alert(checkedValue);
                          setSelectType(checkedValue)
                          if(checkedValue.length==2)
                              setDetailType(2);
                          else
                              setDetailType(1);
                          //刷新表格
                          table_ref.current?.reloadAndRest?.();
                        },
                    }}
                    options={[{value:0,label:'完成报价'},{value:1,label:'已定价'}]}
                         />
                </Space>}
              >
                {JSON.stringify(selectedRecord)}
                 <ProTable<DataType>
                   rowKey='id'
                   columns={columns}
                   search={false}
                   actionRef={table_ref}
                   request={async ()=>{
                    // x_id,cate_id,id,source,fdata
                     const x=await s_getcommontableinfo({x_id:1,cate_id:[],id:0,source:'v_verifyprice',fdata:{type:selectType}});
                   return {
                      data:x.data[0],
                      success:true,
                     }
                   }}
                   rowSelection={{
                    type:'radio',
                    async onChange(selectedRowKeys, selectedRows, info) {
                      setSelectedRecord(selectedRows);
                      //选择对应单据的明细记录，并更新明细表格组件
                      if(selectedRows.length>0){
                      const x=await s_getQuotePrice({ptype:selectedRows[0].querytype,mid:selectedRows[0].id});
                      // alert(JSON.stringify(x.data[0]));
                      //保存最低价，用于批量选择最低价
                      setMinTotal(x.data[1]);
                      setDataSourceByDetail(x.data[0]);
                     } },
                   }}
                  />
              </ProCard>
               
            </Col>
            <Col span={16}>
            <ProCard title='报价明细' style={{height:700}}
                extra={<Space>
                    <Button onClick={()=>chooseMinTotal()}>批量选择最低价</Button>
                    <Button onClick={()=>verifyPrice(1)}>定价</Button>
                    <Button onClick={()=>verifyPrice(2)}>定价并转采购订单</Button>
                </Space>}
               >
                 {selectedRecord.length==1&&selectedRecord[0].querytype==2?
                    <TableByDetail setData={setDataSourceByDetail} data={dataSourceByDetail} editor_ref={editor_ref} />
                   :<TableByVouch  setData={setDataSourceByDetail} data={dataSourceByDetail} editor_ref={editor_ref} />
                 }
                 </ProCard>
            </Col>
          </Row>
    </>
}

export default App;